package XiaoMi;

import java.util.Stack;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class LeetCode02 {
	public static void main(String[] args) {
		String[] tokens = {"-3","9","*"};
//		String[] tokens = {"4"};
		
		System.out.println(evalRPN(tokens));
	}
    public static int evalRPN(String[] tokens) {
        if(tokens == null || tokens.length == 0 ){
            return -1;
        }
        
        Stack<Integer> stack = new Stack<Integer>();
        int num = 0;
        for(int i=0;i < tokens.length;i++){
    		if(isNum(tokens[i])){
    			num = Integer.parseInt(tokens[i]);
    		}else if("+".equals(tokens[i])){
                    int num1 = stack.pop();
                    int num2 = stack.pop();
                    num = num1 + num2;
            }else if("-".equals(tokens[i])){
                int num1 = stack.pop();
                int num2 = stack.pop();
                num = num2 - num1;
            }else if("*".equals(tokens[i])){
                int num1 = stack.pop();
                int num2 = stack.pop();
                num = num1 * num2;
            }else if("/".equals(tokens[i])){
                int num1 = stack.pop();
                int num2 = stack.pop();
                num = num2/num1;
            }else {
				return -1;
			}
    		if(i == tokens.length-1){
                break;
            }else{
                stack.push(num);
            }
            
        }
        return num;
    }
	public static boolean isNum(String str) {
		if(str==null || str.length() == 0){
			return false;
		}
		 Pattern pattern = Pattern.compile("-?[0-9]+"); 
		   Matcher isNum = pattern.matcher(str);
		   if( !isNum.matches() ){
		       return false; 
		   } 
		   return true; 
	}
}
